package cn.jxwazx.sheinspringboot.controller;

import cn.jxwazx.sheinspringboot.entity.BaseColumn;
import cn.jxwazx.sheinspringboot.entity.R;
import cn.jxwazx.sheinspringboot.entity.param.TaskPageParam;
import cn.jxwazx.sheinspringboot.entity.po.Task;
import cn.jxwazx.sheinspringboot.service.TaskService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.ArrayList;
import java.util.function.ObjLongConsumer;
import lombok.RequiredArgsConstructor;
import org.apache.commons.compress.utils.Lists;
import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.util.ObjUtil;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/task")
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class TaskController {

    private final TaskService taskService;

    @PostMapping("/create")
    public Object create(@RequestBody Task task) {
        taskService.save(task);
        return R.success();
    }


    @PostMapping("/remove")
    public Object remove(@RequestBody Task task) {
        taskService.removeById(task);
        return R.success();
    }


    @PostMapping("/update")
    public Object update(@RequestBody Task task) {
        taskService.updateById(task);
        return R.success();
    }


    /**
     * 获取分页列表
     *
     * @param param
     * @return
     */
    @PostMapping("/page")
    public Object page(@RequestBody TaskPageParam param) {
        Page<Task> page = taskService.lambdaQuery()
                .eq(ObjUtil.isNotNull(param.getStatus()), Task::getStatus, param.getStatus())
                .page(param.getPage());
        return R.successPage(page);
    }


    @PostMapping("/start")
    public Object start(@RequestBody Task task) {
        taskService.lambdaUpdate()
                .eq(BaseColumn::getId, task.getId())
                .set(Task::getStatus, 1)
                .update();
        return R.success();
    }

    @PostMapping("/incrementCount")
    public Object incrementCount(@RequestBody Task task) {
        taskService.incrementCount(task);
        return R.success();
    }

    /**
     * 获取任务
     * @return
     */
    @GetMapping("getTask")
    public Object getTask() {
        ArrayList<Object> coll = Lists.newArrayList();
        coll.add(0);
        coll.add(1);

        Task one = taskService.lambdaQuery().in(Task::getStatus, coll).orderByAsc(BaseColumn::getCreateTime)
                .last("LIMIT 1").one();

        if (ObjUtil.isNull(one)) {
            return R.success();
        }
        return R.success(one);
    }
}
